package uk.ac.sanger.das.dasregistry.springrest.security;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.junit.After;
import org.springframework.beans.factory.BeanFactory;




public class Authenticate {
 Logger logger=Logger.getLogger(Authenticate.class);
	CryptoUtils crypt;
	AuthenticationDAO auth;
	
	public AuthenticationDAO getAuth() {
		return auth;
	}
	public void setAuth(AuthenticationDAO auth) {
		this.auth = auth;
	}
	public Authenticate(){
		crypt=new CryptoUtils();
	}
	/**
	 * 
	
	 * @param username:password encoded String
	 * @return true if user authorized false if not
	 */
	public boolean authenticate(String auth){
		// username="jw12@sanger.ac.uk";
		
		
		if (auth == null) return false; // no auth 
		if (!auth.toUpperCase().startsWith("BASIC ")) return false; // we only do BASIC
		// Get encoded user and password, comes after "BASIC " 
		String userpassEncoded = auth.substring(6); // Decode it, using any base 64 decoder 
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); 
		String userpassDecoded = null;
		try {
			userpassDecoded = new String(dec.decodeBuffer(userpassEncoded));
		} catch (IOException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		} // Check our user list to see if that user and password are "allowed"
		//System.out.println("userpass decoded="+userpassDecoded);
		String []userAndPass=userpassDecoded.split(":");		
		if(userAndPass.length!=2){
			logger.warn("no a user and pass present");
			return false;
		}

		String user=userAndPass[0];
		//at the moment we will restrict all update, post and delete functions to the registry admin
		//until we have decided on a decent authorisation structure
		if(!user.equals("dasregistry@sanger.ac.uk"))return false;
		
		String usersPass=crypt.getDigestString(userAndPass[1]);
		
		String databasePass=this.getPassFromDatabase(userAndPass[0]);
		//if empty string something went wrong so return false
		if(databasePass.equals(""))
			{
			logger.debug("databasePass in authenticate method pass is empty string "+usersPass+"="+databasePass);
			return false;
			}
		if(usersPass.equals(databasePass)){
			logger.debug("user pass=database pass "+usersPass+"="+databasePass );
			logger.warn("user "+userAndPass[0]+" is performing and update, add or delete via the web service");
			return true;
		}else{
			logger.debug("user pass does not equal databasePass"+usersPass+"="+databasePass);
			return false;
		}
		
	}
	private String getPassFromDatabase(String username) {
		//get encrypted pass from database and return String representation
		return auth.getEncryptedPass(username);
		
	}
	
	public String addUserWithPass(String username, String unencryptedPassword, String dislayName, int role, int alertMe){
		String errorMessage="";
		//encrypte password and store in database
		String encryptedPassword=crypt.getDigestString(unencryptedPassword);
		
		errorMessage=auth.addUserWithPass(username, dislayName, encryptedPassword, role, alertMe);
		
		return errorMessage;
	}
	
	public String removeUser(String email) {
		String errors=auth.deleteUser(email);
		return errors;
	}
	
	public boolean userExists(String email){
		return auth.userExists(email);
	
	}
	public String updatePassword(String email, String pass) {
		String errorMessage="";
		//encrypte password and store in database
		String encryptedPassword=crypt.getDigestString(pass);
		System.out.println("calling update pass in authenticate with "+encryptedPassword);
		errorMessage=auth.updatePass(email ,encryptedPassword);
		
		return errorMessage;
	}
}
